<template>
  <div class="module-monitor">
    <h4 class="zl-title">
      {{title}}
      <!-- <div class="fr monitor-collapse" @click="fold = !fold" v-if="!podId">
        <Icon type="ios-arrow-down" />
        <span v-if="fold">展开</span>
        <span v-else>收起</span>
      </div> -->
    </h4>
    <div class="monitor-box">
      <Row :gutter="20">
        <Col span="12">
          <Spin fix v-if="isCpuLoading"></Spin>
          <div class="monitor-item" v-else>
            <div id="cpu" class="monitor-cpu" v-show="cpuInfo.length > 0"></div>
            <div class="zl-no-data" v-show="cpuInfo.length === 0">
              CPU使用情况暂无数据！
            </div>
          </div>
        </Col>
        <Col span="12">
          <Spin fix v-if="isMemoryLoading"></Spin>
          <div class="monitor-item" v-else>
            <div id="memory" class="monitor-memory" v-show="memoryInfo.length > 0"></div>
            <div class="zl-no-data" v-show="memoryInfo.length === 0">
              内存使用情况暂无数据！
            </div>
          </div>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script>
  import echarts from 'echarts'

  export default {
    name: 'monitor',
    data() {
      return {
        chartCpu: null,
        chartMemory: null,
        cpuInfo: [],
        memoryInfo: [],
        isCpuLoading: true,
        isMemoryLoading: true,
        timer: null,
        wsMemory: null,
        wsCpu: null,
        isChange: false,
        fold: false
      }
    },
    props: {
      environmentId: {
        type: String,
        default: ''
      },
      title: {
        type: String,
        default: ''
      },
      // 如果podId有，则为容器监控，否则为环境监控
      podId: {
        type: String,
        default: ''
      }
    },
    mounted() {
      // 容器通过mounted触发数据
      if (this.podId) {
        this.init()
      }
    },
    methods: {
      // 初始化
      init() {
        // isChange用于判断环境切换，从而切换websocket接收的数据
        let wsUrl = localStorage.getItem('wsUrl').replace(/http(s?):\/\//gi, '')
        if (this.isChange) {
          if (this.podId) {
            if (!this.wsCpu) {
              this.cpuOpen(wsUrl)
            } else {
              this.wsCpu.send('environmentId=' + this.$route.params.environmentId + ',podId=' + this.podId)
            }
            if (!this.wsMemory) {
              this.memoryOpen(wsUrl)
            } else {
              this.wsMemory.send('environmentId=' + this.$route.params.environmentId + ',podId=' + this.podId)
            }
          } else {
            if (!this.wsCpu) {
              this.cpuOpen(wsUrl)
            } else {
              this.wsCpu.send('environmentId=' + this.$route.params.environmentId)
            }
            if (!this.wsMemory) {
              this.memoryOpen(wsUrl)
            } else {
              this.wsMemory.send('environmentId=' + this.$route.params.environmentId)
            }
          }
        } else {
          this.cpuOpen(wsUrl)
          this.memoryOpen(wsUrl)
        }
      },
      // cpu websocket开启
      cpuOpen(wsUrl) {
        this.wsCpu = new WebSocket('ws://' + wsUrl + '/webSocket/cpuHandle')
        this.wsCpu.onopen = this.wsCpuOnopen
        this.wsCpu.onmessage = this.wsCpuOnmessage
        this.wsCpu.onclose = this.wsCpuOnclose
      },
      // memory websocket开启
      memoryOpen(wsUrl) {
        this.wsMemory = new WebSocket('ws://' + wsUrl + '/webSocket/memory')
        this.wsMemory.onopen = this.wsMemoryOnopen
        this.wsMemory.onmessage = this.wsMemoryOnmessage
        this.wsMemory.onclose = this.wsMemoryOnclose
      },
      wsCpuOnopen() {
        console.log('cpu webSocket开启 - ' + this.$route.params.environmentId + ' - ' + this.podId)
        if (this.podId) {
          this.wsCpu.send('environmentId=' + this.$route.params.environmentId + ',podId=' + this.podId)
        } else {
          this.wsCpu.send('environmentId=' + this.$route.params.environmentId)
        }
      },
      wsCpuOnmessage(evt) {
        if (evt.data && /^\[.*\]$/.test(evt.data)) {
          this.cpuInfo = JSON.parse(evt.data)
          this.isCpuLoading = false
          this.initCpuChart()
        }
      },
      wsCpuOnclose(event) {
        this.isCpuLoading = false
        // eslint-disable-next-line no-trailing-spaces
        this.wsCpu = null
      },
      wsMemoryOnopen() {
        console.log('meomory webSocket开启 - ' + this.$route.params.environmentId + ' - ' + this.podId)
        if (this.podId) {
          this.wsMemory.send('environmentId=' + this.$route.params.environmentId + ',podId=' + this.podId)
        } else {
          this.wsMemory.send('environmentId=' + this.$route.params.environmentId)
        }
      },
      wsMemoryOnmessage(evt) {
        if (evt.data && /^\[.*\]$/.test(evt.data)) {
          this.isMemoryLoading = false
          this.memoryInfo = JSON.parse(evt.data)
          this.initMemoryChart()
        }
      },
      wsMemoryOnclose(event) {
        this.isMemoryLoading = false
        // eslint-disable-next-line no-trailing-spaces
        this.wsMemory = null
      },
      // 初始化echart
      initChart() {
        this.initCpuChart()
        this.initMemoryChart()
      },
      // 初始化cpu chart
      initCpuChart() {
        let vm = this
        // 定义数组timeArr，valueArr，echart的data数据
        let timeArr = []
        let valueArr = []
        for (let i = 0; i < this.cpuInfo.length; i++) {
          timeArr.push(this.cpuInfo[i].time.split(' ')[1]) // 分割字符串取时间
          valueArr.push(this.cpuInfo[i].value)
        }
        vm.$nextTick(function () {
          let cpuObj = document.getElementById('cpu')
          if (!cpuObj) {
            return
          }
          if (vm.chartCpu) {
            // 防止渲染后宽度为0，再次渲染时无法展示内容问题
            vm.chartCpu.resize('auto')
          } else {
            vm.chartCpu = echarts.init(cpuObj)
          }
          vm.chartCpu.setOption({
            backgroundColor: '#fff',
            title: {
              top: 20,
              text: 'cpu使用情况',
              textAlign: 'center',
              textStyle: {
                fontWeight: 'normal',
                fontSize: 16,
                color: '#666'
              },
              left: '50%'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                lineStyle: {
                  color: '#57617B'
                }
              }
            },
            legend: {
              top: 20,
              icon: 'rect',
              itemWidth: 14,
              itemHeight: 5,
              itemGap: 13,
              data: ['cpu'],
              right: '4%',
              textStyle: {
                fontSize: 12,
                color: '#7a7979'
              }
            },
            grid: {
              top: 100,
              left: '4%',
              right: '12%',
              bottom: '2%',
              containLabel: true
            },
            xAxis: [{
              type: 'category',
              name: '时间(分)',
              boundaryGap: true,
              axisLine: {
                lineStyle: {
                  color: '#7a7979'
                }
              },
              splitLine: {
                lineStyle: {
                  type: 'dashed',
                  color: '#F1F1F3'
                }
              },
              data: timeArr
            }],
            yAxis: [{
              type: 'value',
              name: 'CPU(mCpu)',
              axisTick: {
                show: false
              },
              axisLine: {
                lineStyle: {
                  color: '#7a7979'
                }
              },
              axisLabel: {
                margin: 10,
                textStyle: {
                  fontSize: 14
                }
              },
              splitLine: {
                lineStyle: {
                  color: '#c1c0c0',
                  type: 'dashed'
                }
              }
            }],
            series: [{
              name: 'cpu',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 5,
              showSymbol: false,
              lineStyle: {
                normal: {
                  width: 2
                }
              },
              areaStyle: {
                normal: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(0, 136, 212, 0.3)'
                  }, {
                    offset: 0.8,
                    color: 'rgba(0, 136, 212, 0.0)'
                  }], false),
                  shadowColor: 'rgba(0, 136, 0, 0.0)',
                  shadowBlur: 10
                }
              },
              itemStyle: {
                normal: {
                  color: 'rgb(0,136,212)',
                  borderColor: 'rgba(0,136,212,0.2)',
                  borderWidth: 12
                }
              },
              data: valueArr
            }]
          })
        })
      },
      // 初始化内存chart
      initMemoryChart() {
        let vm = this
        // 定义数组timeArr，valueArr，echart的data数据
        let timeArr = []
        let valueArr = []
        for (let i = 0; i < vm.memoryInfo.length; i++) {
          timeArr.push(vm.memoryInfo[i].time.split(' ')[1]) // 分割字符串取时间
          valueArr.push(vm.memoryInfo[i].valueOfGi)
        }
        vm.$nextTick(function () {
          let memoryObj = document.getElementById('memory')
          if (!memoryObj) {
            return
          }
          if (vm.chartMemory) {
            // 防止渲染后宽度为0，再次渲染时无法展示内容问题
            vm.chartMemory.resize('auto')
          } else {
            vm.chartMemory = echarts.init(memoryObj)
          }
          vm.chartMemory.setOption({
            backgroundColor: '#fff',
            title: {
              top: 20,
              text: '内存使用情况',
              textStyle: {
                fontWeight: 'normal',
                fontSize: 16,
                color: '#666'
              },
              left: '50%',
              textAlign: 'center'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                lineStyle: {
                  color: '#57617B'
                }
              }
            },
            legend: {
              top: 20,
              icon: 'rect',
              itemWidth: 14,
              itemHeight: 5,
              itemGap: 13,
              data: ['memory'],
              right: '4%',
              textStyle: {
                fontSize: 12,
                color: '#7a7979'
              }
            },
            grid: {
              top: 100,
              left: '4%',
              right: '12%',
              bottom: '2%',
              containLabel: true
            },
            xAxis: [{
              type: 'category',
              name: '时间(分)',
              boundaryGap: true,
              axisLine: {
                lineStyle: {
                  color: '#7a7979'
                }
              },
              splitLine: {
                lineStyle: {
                  type: 'dashed',
                  color: '#c1c0c0'
                }
              },
              data: timeArr
            }],
            yAxis: [{
              type: 'value',
              name: '内存(GiB)',
              axisTick: {
                show: false
              },
              axisLine: {
                lineStyle: {
                  color: '#7a7979'
                }
              },
              axisLabel: {
                margin: 10,
                textStyle: {
                  fontSize: 14
                }
              },
              splitLine: {
                lineStyle: {
                  color: '#c1c0c0',
                  type: 'dashed'
                }
              }
            }],
            series: [{
              name: 'memory',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 5,
              showSymbol: false,
              lineStyle: {
                normal: {
                  width: 2
                }
              },
              areaStyle: {
                normal: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(137, 189, 27, 0.3)'
                  }, {
                    offset: 0.8,
                    color: 'rgba(137, 189, 27, 0)'
                  }], false),
                  shadowColor: 'rgba(0, 0, 0, 0.1)',
                  shadowBlur: 10
                }
              },
              itemStyle: {
                normal: {
                  color: 'rgb(137,189,27)',
                  borderColor: 'rgba(137,189,2,0.27)',
                  borderWidth: 12

                }
              },
              data: valueArr
            }]
          })
        })
      }
    },
    watch: {
      environmentId(val, oldVal) {
        if (oldVal) {
          this.isChange = true
        }
        this.fold = true
        this.init()
      }
    },
    beforeDestroy() {
      this.wsCpu && this.wsCpu.close()
      this.wsMemory && this.wsMemory.close()
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.module-monitor {
  .ivu-icon {
    transition: all 0.3s ease;
    transform: rotate(0)
  }
  &.fold {
    .monitor-box {
      height: 0;
      overflow: hidden;
    }
    .ivu-icon {
      transform: rotate(90deg)
    }
  }
  .monitor-box {
    position: relative;
    transition: all 0.3s ease;
    height: 330px;
    [class*="monitor-"] {
      height: 300px;
      border: 1px solid #eee;
      border-radius: 4px;
      overflow: hidden;
      background-color: #f5f5f5;
    }
    .zl-no-data {
      line-height: 240px;
      border: 1px solid #eee;
      border-radius: 4px;
      background-color: #f5f5f5;
    }
  }
}
.monitor-box /deep/ {
  .ivu-col {
    position: relative;
    height: 330px;
  }
}
.monitor-collapse {
  font-size: 20px;
  cursor: pointer;
  color: #2d8cf0;
  span {
    font-size: 14px;
  }
}
</style>
